//
//  NetworkingTools.m
//  Emoticon
//
//  Created by 袁量 on 2017/8/15.
//  Copyright © 2017年 袁量. All rights reserved.
//

#import "NetworkingTools.h"
static NetworkingTools *tools = nil;
NSString *urlString_Default = @"http://118.89.115.175:8080/index.php/api/";
@implementation NetworkingTools
+ (instancetype)ShareManager{
//    static NetworkingTools *tools;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tools = [[self alloc] init];
        tools.responseSerializer.acceptableContentTypes = [tools.responseSerializer.acceptableContentTypes setByAddingObject:@"text/html"];
        
    });
    return tools;
}
+ (instancetype)allocWithZone:(struct _NSZone *)zone{
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        tools = [super allocWithZone:zone];
    });
    return tools;
}
- (id)copyWithZone:(NSZone *)zone{
    return tools;
}
- (void)requestWithmethodType:(RequestType)methodType urlString:(NSString *)urlString parameters:(id)parameters finished:(void (^)(id result, NSError *error))finished{
    urlString = urlString == nil ? urlString_Default: urlString;
    void (^successCallBack)(NSURLSessionDataTask * _Nonnull task,id  _Nullable result) = ^(NSURLSessionDataTask * _Nonnull task,id  _Nullable responseObject){
        finished(responseObject,nil);
    };
    void (^failureCallBack)(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) = ^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finished(nil,error);
    };
    if (methodType == 0) {
//        GET 方式
        [self GET:urlString parameters:parameters progress:^(NSProgress * _Nonnull downloadProgress) {
            
        } success:successCallBack failure:failureCallBack];
    }else{
//        POST 方式
        [self POST:urlString parameters:parameters progress:^(NSProgress * _Nonnull uploadProgress) {
            
        } success:successCallBack failure:failureCallBack];
    }
}
- (void)uploadWithImg:(UIImage *)img finished:(void (^)(id result, NSError *error))finished{
    [self POST:@"http://118.89.115.175:8080/index.php/api/upload" parameters:nil constructingBodyWithBlock:^(id<AFMultipartFormData>  _Nonnull formData) {
        NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
        
        formatter.dateFormat = @"yyyyMMddHHmmss";
        
        NSString *fileName = [NSString stringWithFormat:@"%@.png",[formatter stringFromDate:[NSDate date]]];
        
        [formData appendPartWithFileData:UIImagePNGRepresentation(img) name:@"uploadFile" fileName:fileName mimeType:@"image/png"];
        
    } progress:nil success:^(NSURLSessionDataTask * _Nonnull task, id  _Nullable responseObject) {
        finished(responseObject,nil);
    } failure:^(NSURLSessionDataTask * _Nullable task, NSError * _Nonnull error) {
        finished(nil,error);
    }];
}

@end
